//商家模块数据
import {
    ADD_FOOD_COUNT,
    REDUCE_FOOD_COUNT,
    CLEAR_ALL, GET_ONESHOP
} from "../mutation-types";
import Vue from "vue";
import {
    reqOneShop
} from '@/api/index.js'
import {getCartFoods} from '@/utils/utils.js'
export default {
    state: {
        shopCart: [],
        shop:{}
    },
    mutations: {
        //购物车添加食品数量
        [ADD_FOOD_COUNT](state, {food}) {
            if (food.count) {
                food.count++
            } else {
                //如果没有count，就为food添加一个count属性，并将food放到shopCart里
                Vue.set(food, 'count', 1)
                state.shopCart.push(food)
            }
        },
        //购物车减少食品数量
        [REDUCE_FOOD_COUNT](state, {food}) {
            if (food.count > 0) {
                food.count--
                //数量为0时，也就是从1变为0，则将该食物从购物车数组里删除
                if (food.count === 0) {
                    state.shopCart.splice(state.shopCart.indexOf(food), 1)
                }
            }
        },
        //清空购物车
        [CLEAR_ALL](state){
            state.shopCart.forEach((item)=>{
                item.count=0
            })
            state.shopCart=[]
        },
        //根据id获得单个商户信息
        [GET_ONESHOP](state,{shop,shopCart}){
            state.shop=shop
            state.shopCart=shopCart
        }
    },
    actions: {
        //修改对应的food数量
        polishFood({commit}, {isAdd, food}) {
            if (isAdd) {
                //为真，则添加一个
                commit(ADD_FOOD_COUNT, {food})
            } else {
                //为假，减少一个
                commit(REDUCE_FOOD_COUNT, {food})
            }
        },
        //清空购物车
        clearAll({commit}){
            commit(CLEAR_ALL)
        },
        //根据id得到不同商户信息
        async getOneShop({commit},id){
            const result = await reqOneShop(id)
            if(result.code===0){
                //读取得到当前商家的购物车Food数组
                const shopCart=getCartFoods(result.data)
                commit(GET_ONESHOP,{shop:result.data,shopCart})
            }

        }
    },
    getters: {
        //购物车总数量
        totalCount(state) {
            return state.shopCart.reduce((adder, item) => {
                adder += item.count
                return adder
            }, 0)
        },
        //购物车总价格
        totalPrice(state) {
            return state.shopCart.reduce((adder, item) => {
                 adder +=item.count * item.price
                return adder
            }, 0)
        },
    }
}